﻿using DevExpress.Data.Filtering;
using DevExpress.Data.Filtering.Helpers;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.Blazor.Components.Models;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Layout;
using DevExpress.ExpressApp.Model.NodeGenerators;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.ExpressApp.Templates;
using DevExpress.ExpressApp.Utils;
using DevExpress.Office.Utils;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.BaseImpl;
using DevExpress.Persistent.Validation;
using HC.XAP.FileDecode.Blazor.Server.Editors.FileUpload;
using HC.XAP.FileDecode.Module.BusinessObjects.FileDecode;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Text;

namespace HC.XAP.FileDecode.Blazor.Server.Controllers
{
    // For more typical usage scenarios, be sure to check out https://documentation.devexpress.com/eXpressAppFramework/clsDevExpressExpressAppViewControllertopic.aspx.
    public partial class UploadInPopupController : ViewController<ListView>
    {

        private string upLoadFilePath = $"D:\\temp\\";
        public UploadInPopupController()
        {
            TargetObjectType = typeof(HCOBFileDecode);
            var customUploadFileAction = new PopupWindowShowAction(this, "CustomUploadFileAction", PredefinedCategory.View)
            {
                Caption = "上传文件",
                ImageName = "AddFile",
                TargetViewType = ViewType.ListView
                
            };
            customUploadFileAction.Execute += CustomUploadFileAction_Execute;
            customUploadFileAction.CustomizePopupWindowParams += CustomUploadFileAction_CustomizePopupWindowParams;
        }
        private async void CustomUploadFileAction_Execute(object sender, PopupWindowShowActionExecuteEventArgs e)
        {
            var fileStreams = HC.XAP.MultipleFileUpload.FileUploadHelper;
            int i = 1;
            foreach(var stream in fileStreams)
            {
                var filename = $"tempfile{i}.png";
                var decodeFile = ObjectSpace.CreateObject<HCOBFileDecode>();
                FileData fileCopy = ObjectSpace.CreateObject<FileData>();
                
                var s = new MemoryStream(stream.ToArray());
                fileCopy.LoadFromStream(filename,s);
                decodeFile.File = fileCopy;//保存文件到数据库
                await SaveFileToDisk($"{upLoadFilePath}{filename}", s);//保存文件到硬盘指定目录里

                
            }
            var tag = e.PopupWindowViewCurrentObject as UploadFileParameters;
            var file = tag.FileUpload;
            ObjectSpace.CommitChanges();
            ObjectSpace.Refresh();
            this.View.Refresh();
        }
        private void CustomUploadFileAction_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            NonPersistentObjectSpace os = (NonPersistentObjectSpace)e.Application.CreateObjectSpace(typeof(UploadFileParameters));
            os.PopulateAdditionalObjectSpaces(Application);
            e.DialogController.SaveOnAccept = false;
            e.View = e.Application.CreateDetailView(os, os.CreateObject<UploadFileParameters>());
        }

        private async Task<bool> SaveFileToDisk(string fileName, MemoryStream stream)
        {
            using (FileStream file = new FileStream(fileName, FileMode.Create, System.IO.FileAccess.Write))
            {
                await file.WriteAsync(stream.ToArray());
                file.Close();
                return true;
            }
            
        }

        //private async void WriteFileToDisk(string fileName,MemoryStream stream)
        //{
        //    using (
        //               var reader =
        //                   new FileStream(
        //                       fileName,
        //                       FileMode.Create))
        //    {
        //       await stream.CopyToAsync(reader);
        //    }
        //}

    }

    [DomainComponent]
    public class UploadFileParameters : NonPersistentObjectImpl
    {
        private FileData file;
        [ExpandObjectMembers(ExpandObjectMembers.Never)]
     
        private string _FileUpload;
        [EditorAlias("FileUploadEditor")]
        public string FileUpload
        {
            get { return _FileUpload; }
            set { SetPropertyValue(ref _FileUpload, value); }
        }

        
    }
}
